<template>
  <el-form  ref="ruleFormRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
    <el-form-item label="主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small"/>
    </el-form-item>
    <el-form-item label="员工" prop="staffId">
      <el-select v-model="formData.staffId" placeholder="请选择员工" filterable size="small" @change="staffChange">
        <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="部门" prop="oaDeptId">{{ dept && dept.name ? dept.name : '-' }}</el-form-item>
    <el-form-item label="职务" prop="postId">{{ post && post.name ? post.name : '-' }}</el-form-item>
    <el-form-item label="职位" prop="oaPositionId">
      <span>{{ position && position.name ? position.name : '-' }}</span>
      <span style="margin-left: 20px">职级 {{ position && position.gradeName ? position.gradeName : '-' }}</span>
    </el-form-item>
    <el-form-item label="入职日期" prop="occurDate">{{ formData.occurDate }}</el-form-item>
    <el-form-item label="试用期" prop="trialTerm">
      <span v-for="item in dictMap['StaffTrialLimit']" :key="item.value" v-show="item.value == formData.trialTerm">{{ item.name }}</span>
    </el-form-item>
    <el-form-item label="实际转正日期" prop="endDate">
      <el-date-picker v-model="formData.endDate" type="date" placeholder="请选择实际转正日期" size="small" value-format="YYYY-MM-DD" @change="dateChange"/>
    </el-form-item>
    <el-form-item label="备注信息" prop="remark">
      <el-input v-model="formData.remark" type="textarea" placeholder="请填写备注信息" :rows="3" size="small"/>
    </el-form-item>
    <el-form-item label="优先度">
      <el-radio-group v-model="formData.priority" size="small">
        <el-radio :label="0" size="small">普通</el-radio>
        <el-radio :label="1" size="small">高</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>

<script>
// 转正 OA_OFFICIAL
import {onMounted, reactive, toRefs,ref, nextTick, watch} from 'vue'
import {listByState, getStaffById} from '/@/api/oa/staff'
import {getDictByCodes} from '/@/api/sys/dict'
import {formatDate} from '/@/utils/formatTime'
import { homeApi } from "/@/api/home/index";
// import { format } from "/@/views/home/component/lib/utils";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'ToOffcialForm',
    props: {
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props, context) {
        const { editId, selectTime } = toRefs(props)
        const homeCalendar = homeApi();
        const ruleFormRef = ref({});
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            formData: {
                staffId: null,
                title: '员工转正',
                oaDeptId: null,  // oa系统部门id
                postId: null,   // oa系统职务id
                oaPositionId: null,   // oa系统职位id
                occurDate: null,  // 入职日期
                trialTerm: null,  // 试用期 字典StaffTrialLimit
                endDate: formatDate(new Date(), 'YYYY-mm-dd'),  // 实际转正日期
                remark: null,
                state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
                priority: 0        // 优先级 0普通 1重要
            },

            dept: null,
            post: null,
            position: null,
            dictMap: {},
            staffList: [],
            originForm: {}
        })
        const formRules = reactive({
        staffId: {required: true, message: '请选择员工', trigger: 'change'},
            title: {required: true, message: '请填写主题', trigger: 'blur'},
            endDate: {required: true, message: '请选择实际转正日期', trigger: 'change'}
        });
        let close = () => {
            context.emit("ChiShaiormClose");
            reset()
        };

        let submit = () => {
            if (!ruleFormRef) return;
            return new Promise(async (resolve, reject) => {
                await ruleFormRef.value.validate((valid, fields) => {
                    if (valid) {
                        if(editId.value) {
                            // 编辑
                            for(let key in state.formData){
                              if(state.originForm.hasOwnProperty(key)){
                                  state.originForm[key] = state.formData[key]
                              }
                              if(state.originForm.info.hasOwnProperty(key)){
                                  state.originForm.info[key] = state.formData[key]
                              }
                            }
                            storesCalendarConfig.setEventForm(state.originForm)
                            reset()
                            close()
                            resolve('edit') 
                        }else{
                            homeCalendar.addOfficial(state.formData).then((res) => {
                                if (res.code === 0) {
                                    reset()
                                    close()
                                    resolve()
                                }else{
                                    reject()
                                }
                            });
                        }
                    } else {
                        reject()
                        console.log("error submit!", fields);
                    }
                });
            })
        };
        const reset = () => {
            if (!ruleFormRef) return
            ruleFormRef.value.resetFields()
        }

        const getStaffData = async () => {
            try {
                const res = await listByState('1')
                state.staffList = res.data
            } catch (e) {
                console.log(e)
            }
        }
        const staffChange = async (val) => {
            const res = await getStaffById(val)
            state.dept = res.data.dept
            if (state.dept) {
                state.formData.oaDeptId = state.dept.id
            }
            state.post = res.data.officePost
            if (state.post) {
                state.formData.postId = state.post.id
            }
            state.position = res.data.officePosition
            if (state.position) {
                state.formData.oaPositionId = state.position.id
            }
            state.formData.occurDate = res.data.joinedDate
            state.formData.trialTerm = res.data.trialDay
        }
        const dateChange = val => {}
        
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
              })
            }
          }        
        )
        onMounted(() => {
            getDictByCodes(['StaffTrialLimit']).then(res => state.dictMap = res.data)
            getStaffData()
            if (state.formData.staffId) {
                staffChange(state.formData.staffId)
            }
            nextTick(() => {
                if(!editId.value && selectTime.value) {
                    state.formData.endDate = selectTime.value.substring(0,10)
                }
            })
        })
        return {
            ...toRefs(state),
            getStaffData,
            staffChange,
            dateChange,
            submit,
            close,
            formRules,
            ruleFormRef,
            reset,
        }
    }
}
</script>

<style>

</style>